package com.qike.duola.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.qike.duola.domain.DuolaCar;
import com.qike.duola.domain.SysUserWithBLOBs;
import com.qike.duola.dto.CarLocationVo;
import com.qike.duola.dto.LocationEntity;
import com.qike.duola.enums.CarTransStatusEnums;
import com.qike.duola.mapper.DuolaCarMapper;
import com.qike.duola.mapper.SysUserMapper;
import com.qike.duola.service.BaseService;
import com.qike.duola.service.DuolaTransOrderService;
import com.qike.duola.socket.NewCarLocationSocket;
import com.qike.duola.vo.FixInfoVo;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 * @Author: Eric.zhou
 * @Date: 2020/9/24 18:21
 */
@Service
public class BaseServiceImpl implements BaseService {

    @Value("${huaji.lat}")
    private String lat;
    @Value("${huaji.lng}")
    private String lng;
    @Value("${huaji.name}")
    private String name;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private DuolaCarMapper carMapper ;

    @Autowired
    private NewCarLocationSocket carLocationSocket;
    @Autowired
    private DuolaTransOrderService transOrderService;
    @Autowired
    private SysUserMapper sysUserMapper;



    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    @Override
    public String upLoadPhoto(MultipartFile file) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region0());
//...其他参数参考类注释

        UploadManager uploadManager = new UploadManager(cfg);
//...生成上传凭证，然后准备上传
        String accessKey = "XXIFDSFml6O1vjrvvggHiKd7V00vuC0yP0SU6Q_4";
        String secretKey = "5SvAdizQq_dvxwV0ERHOaB_xhhp0vu-VtHyMFv5Q";
        String bucket = "baojie58";

//默认不指定key的情况下，以文件内容的hash值作为文件名
//        String key = file.getName();
        String key = file.getOriginalFilename();

        try {
//            byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");
            byte[] uploadBytes = file.getBytes();
            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(uploadBytes);
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);

            try {
                Response response = uploadManager.put(byteInputStream, key, upToken, null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
                return "https://cdn.fledchina.com/" + putRet.key;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception ex) {
            //ignore
        }


        return null;
    }

    /**
     * 搅拌站信息
     *
     * @return
     */
    @Override
    public FixInfoVo fixInfo() {
        FixInfoVo vo = new FixInfoVo();
        vo.setLat(lat);
        vo.setLng(lng);
        vo.setName(name);
        return vo;
    }

    /**
     * 测试模拟车辆运行
     *
     * @param locationEntity
     */
    @Override
    public void testCarRun(LocationEntity locationEntity) throws IOException {
        //redis 取出车辆信息
        DuolaCar car = null;
        if (redisTemplate.opsForValue().get(locationEntity.getTerminalPhone().substring(1))!=null){
            car = JSONObject.parseObject(redisTemplate.opsForValue().get(locationEntity.getTerminalPhone().substring(1)).toString(),DuolaCar.class) ;
        }
        //发送长连接
        if (car==null) {
            car = carMapper.selectByDeviceId(locationEntity.getTerminalPhone().substring(1));
            if (car!=null){
                redisTemplate.opsForValue().set(locationEntity.getTerminalPhone().substring(1),JSON.toJSONString(car));
            }
        }
        CarLocationVo vo = new CarLocationVo();
        vo.setCarNo(car.getCarNo());
        vo.setId(car.getId());
        vo.setCarType(car.getCarType());
        vo.setDirection(locationEntity.getDirection().toString());
        vo.setElevation(locationEntity.getElevation().toString());
        vo.setLatitude(locationEntity.getLatitude().doubleValue());
        vo.setLongitude(locationEntity.getLongitude().doubleValue());
        vo.setSpeed(locationEntity.getSpeed().toString());
        SysUserWithBLOBs sysUserWithBLOBs = sysUserMapper.selectByPrimaryKey(car.getDriverId());
        if (sysUserWithBLOBs!=null){
            vo.setName(sysUserWithBLOBs.getNickname());
        }
        vo.setModel(car.getCapacity());
        vo.setStatus(car.getTransStatus());
        if (car.getTransStatus()!=null){
            vo.setStatusStr(CarTransStatusEnums.statOf(car.getTransStatus()).getEmsg());
        }
        //判断车辆位置状态
        transOrderService.transStatus(vo);
        //获取车辆历史总量
        Double history = transOrderService.history(car.getId());
        vo.setHistory(history);
        carLocationSocket.sendMessage(JSON.toJSONString(vo));
        //更新车辆经纬度和速度
        car.setLatitude(locationEntity.getLatitude().toString());
        car.setLongitude(locationEntity.getLongitude().toString());
        car.setDirection(locationEntity.getDirection().toString());
        carMapper.updateByPrimaryKeySelective(car);
    }
}
